package view
{
	import events.*;
	
	import flash.events.MouseEvent;
	
	import models.Model;
	
	import mx.binding.utils.BindingUtils;
	import mx.binding.utils.ChangeWatcher;
	import mx.controls.Alert;
	
	import spark.components.Button;
	import spark.components.DataGroup;
	import spark.components.List;
	import spark.components.TextInput;
	import spark.components.supportClasses.SkinnableComponent;
	
	[Event(name="search", type="events.SearchEvent")]
	public class ImageDrawer extends SkinnableComponent
	{
		[SkinPart] public var  searchBar:TextInput;
		[SkinPart] public var  searchButton:Button;		
		[SkinPart] public var  imagesList:List;
			
		public var model:Model;
		
		private var watcher:ChangeWatcher;
		
		
		public function ImageDrawer()
		{			
			super();			
		}				
		
		override protected function partAdded(partName:String, instance:Object):void
		{
			super.partAdded(partName, instance);
			
			if (instance == searchButton)
			{
				searchButton.addEventListener(MouseEvent.CLICK, handleSearchButtonClick);
			}			
			if (instance == imagesList)
			{					
				watcher = BindingUtils.bindProperty(imagesList,"dataProvider",model,"flickrImages");
			}
		}		
		
		override protected function partRemoved(partName:String, instance:Object):void
		{
			super.partRemoved(partName,instance);
			
			if (instance == searchButton)
			{
				searchButton.removeEventListener(MouseEvent.CLICK, handleSearchButtonClick);
			}
			if (instance == imagesList)
			{					
				watcher.unwatch();
			}
				
		}
		protected function handleSearchButtonClick(event:MouseEvent):void
		{
			dispatchEvent(new SearchEvent(SearchEvent.SEARCH, 
				searchBar.text));

		}
		

	}
}
